package org.rainbowinverted.charging.device.connect.bl.server.handler;

import cn.hutool.core.util.HexUtil;
import com.dix.codec.bkv.BKV;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.rainbowinverted.charging.device.connect.bl.server.message.out.BlDeviceHeartbeatOut;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 设备连接处理程序
 *
 * @author huaiping
 */
@Slf4j
@Component
@ChannelHandler.Sharable
@AllArgsConstructor
public class BlDeviceHeartbeatHandler extends BlAbstractHandler<Void, BlDeviceHeartbeatOut> {

    @Override
    public void write(BlDeviceHeartbeatOut message, BKV bkv) {
        addTime(bkv, message.getTime());
    }

    @Override
    public void read(ChannelHandlerContext channelHandlerContext, BKV bkv) {
        // 设备编号
        Long deviceNo = getDeviceNo(bkv);
        // 版本号
        String version = bkv.get(0x04).getStringValue();
        // 信号强度
        Integer gsm = Integer.parseInt(HexUtil.encodeHexStr(bkv.get(0x05).getValue()), 16);
        // 回复设备
        BlDeviceHeartbeatOut heartbeatOut = new BlDeviceHeartbeatOut(deviceNo, getSerialNo(bkv), LocalDateTime.now());
        channelHandlerContext.writeAndFlush(heartbeatOut);
        // 如果MAP中没有通道上下文信息则表示设备新上线
        if (!getOnlineStatus(deviceNo)) {
            putChannel(deviceNo, channelHandlerContext);
        }
    }

}
